import React, { useState, useEffect } from 'react';
import { Button, Table, Space, Input, Breadcrumb, Form, Modal, Checkbox, message, Switch, DatePicker} from 'antd';
import { DatabaseOutlined, RedoOutlined, SearchOutlined } from '@ant-design/icons';
import { useNavigate, useParams } from 'react-router-dom';
import { getRoleList, getRoleById, deleteRole, updateRole } from '../../service/role'; 
import dayjs from 'dayjs';

const { confirm } = Modal;

const Roles = () => {

    const [roleData, setRoleData] = useState([]);
    const [filteredData, setFilteredData] = useState([]);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [modalContent, setModalContent] = useState('');
    const [modalTitle, setModalTitle] = useState('');

    const { id } = useParams();
    const [form] = Form.useForm();
    const navigate = useNavigate();

    //发送接口获取数据/role/list
    useEffect(() => {
        fetchRoleList();
      }, []);
  
    const fetchRoleList = () => {
        getRoleList().then((response) => {
          console.log(response.data);
          setRoleData(response.data.result);
          setFilteredData(response.data.result);
        });
    };

    // 发送接口请求/role/get/:id
    // useEffect(() => {
    //     if (id) {
    //       getRoleById(id).then((response) => {
    //         const { code, result } = response.data;
    //         if (code === 1 && result) {
    //           const data = { ...result};
    //           setRoleData(data);
    //           console.log(data);
    //           form.setFieldsValue(data);
    //         }
    //       });
    //     }
    //   }, []);

    // 实现switch状态修改
    const handleSwitchChange = (record, checked) => {
      console.log('Switch changed:', record.id, checked);
      // Update the role data with the new switch state
      const updatedData = filteredData.map(role => {
          if (role.id === record.id) {
              return { ...role, ifused: checked };
          }
          return role;
      });
      setFilteredData(updatedData);
    };

    //实现查询和重置功能
    const [searchText, setSearchText] = useState('');

    const handleSearch = () => {
        const filtered = roleData.filter(role =>
            role.name.toLowerCase().includes(searchText.toLowerCase())
        );
        setFilteredData(filtered);
    };

    const handleReset = () => {
        setSearchText('');
        setFilteredData(roleData);
    };

    // 实现点击按钮后弹窗
    const showModal = (record) => {
        setModalTitle('编辑角色');

        getRoleById(record.id).then((response) => {
            const { code, result } = response.data;
            if (code === 1 && result) {
              const data = { ...result, createDate: dayjs(result.createDate)};
              setRoleData(data);
              console.log(data);
              form.setFieldsValue(data);
            }
        });

        setModalContent(
            <Form form={form} onFinish={onFinish}>
              <Form.Item name="id" label="编号">
                <Input disabled/>
              </Form.Item>
              <Form.Item name="name" label="姓名">
                <Input />
              </Form.Item>
              <Form.Item name="description" label="描述">
                <Input />
              </Form.Item>
              <Form.Item name="userNum" label="用户数">
                <Input />
              </Form.Item>
              <Form.Item name="createDate" label="创建时间">
                <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" placeholder="请选择时间" />
              </Form.Item>
              <Form.Item name="ifused" label="是否启用" valuePropName="checked">
                <Checkbox />
              </Form.Item>
            </Form>
        );
        setIsModalOpen(true);
    };

    const onFinish =(values)=>{
        const data = {
            ...roleData,
            ...values,
            createDate: values.createDate.format('YYYY-MM-DD HH:mm:ss')
          };
      
          updateRole(values.id, data).then((response) => {
            console.log(response.data);
            const { code, msg } = response.data;
            if (code === 1) {
              message.success(msg);
              setIsModalOpen(false);
            }
        });
    }

    const handleOk = () => {
        form.submit();
    }
  
    const handleCancel = () => {
        setIsModalOpen(false);
    };

    // 实现删除
    const handleDelete = (id) => {
        confirm({
          title: '确认删除吗',
          okText: '确认',
          cancelText: '取消',
          onOk(){
            return deleteRole(id).then((response) => {
              const { code, msg } = response.data;
              if (code === 1) {
                message.success(msg);
                fetchRoleList();
              }
            });
          },
        });
      };

    const columns = [
      {
        title: '编号',
        dataIndex: 'id',
        key: 'id'
      },
      {
        title: '角色名称',
        dataIndex: 'name',
        key: 'name'
      },
      {
          title: '描述',
          dataIndex: 'description',
          key: 'description',
      },
      {
          title: '用户数',
          dataIndex: 'userNum',
          key: 'userNum',
      },
      {
          title: '添加时间',
          dataIndex: 'createDate',
          key: 'createDate',
      },
      {
          title: '是否启用',
          dataIndex: 'ifused',
          key: 'ifused',
          render: (text, record) => (
            <Switch checked={record.ifused} 
                    onChange={(checked) => handleSwitchChange(record, checked)}
                    style={{ width: '40px' }}/>
        ),
      },
      {
          title: '操作',
          key: 'operation',
          render: (text,record) => (
            <Space size="">
              <Button type='link' style={{width: '80px', marginLeft:'-20px'}} 
                        onClick={() => navigate('/roleAllo/'+record.id)}>分配角色</Button>
              <Button type='link' style={{width: '80px'}}
                        onClick={() => navigate('/resourceAllo/'+record.id)}>分配资源</Button>
              <Button type='link' style={{width: '50px'}}
                        onClick={() => showModal(record)}>编辑</Button>
              <Button type='link' style={{width: '50px'}}
                        onClick={() => handleDelete(record.id)}>删除</Button>
            </Space>
        ),
      },
    ];
    
    return (
        <div className='datalist-container'>
            <Breadcrumb
              style={{
                margin: '16px 0',
              }}
            >
              <Breadcrumb.Item>权限</Breadcrumb.Item>
              <Breadcrumb.Item>角色</Breadcrumb.Item>
            </Breadcrumb>
            <div className='select' 
                style={{
                    width: '100%',
                    height: '100px',
                    display: 'flex',
                    border: '1px solid #ccc',
                    borderRadius: '5px'
                }}>
                    <SearchOutlined style={{ marginLeft: '20px', marginTop: '-50px'}}/>
                    <span style={{ 
                        // flex: 1, 
                        marginLeft: '10px',
                        fontSize: '16px',
                        marginTop: '12px',
                        }}>
                        筛选搜索
                    </span> 
                    <span style={{ 
                        // flex: 1, 
                        marginLeft: '-20px',
                        fontSize: '16px',
                        marginTop: '50px'
                        }}>
                        输入搜索：
                    </span> 
                    <Input size='large' placeholder='角色名称' 
                        value={searchText} onChange={(e) => setSearchText(e.target.value)}
                        style={{
                            width: '200px',
                            height: '30px',
                            marginTop: '45px'
                        }}/>
                    <Button icon={<RedoOutlined />}
                            style={{
                                height: '40px',
                                width: '100px',
                                marginLeft: '50px',
                                marginTop: '40px'
                            }}
                            onClick={handleReset}>
                        重置
                    </Button>
                    <Button type="primary" 
                            icon={<SearchOutlined />} 
                            style={{
                                height: '40px',
                                width: '100px',
                                marginLeft: '10px',
                                marginTop: '40px'
                            }}
                            onClick={handleSearch}>
                        查询
                    </Button>
            </div>
            <div className='datalist-header'
                style={{
                    width: '100%',
                    height: '50px',
                    display: 'flex',
                    border: '1px solid #ccc',
                    borderRadius: '5px',
                    marginTop: '20px'
                }}>
                <DatabaseOutlined style={{ marginLeft: '8px' }} /> 
                <span style={{ 
                        flex: 1, 
                        marginLeft: '10px',
                        fontSize: '16px',
                        marginTop: '12px'
                        }}>
                    数据列表
                </span> 
                <Button htmlType='submit' 
                        style={{ 
                            width: '80px',
                            height: '30px',
                            marginRight: '20px',
                            marginTop: '10px' 
                        }}
                        onClick={()=> navigate('/role/add')}>
                    添加
                </Button>
            </div>
            <div className='datalist-body'>
                <Table
                    columns={columns}
                    dataSource={filteredData}
                    rowKey={'id'}
                    style={{ marginTop: '20px'}}
                />
            </div>
            <Modal title={modalTitle} open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                {modalContent}
            </Modal>
        </div>
    )
};

export default Roles;